import { InboxOutlined } from '@ant-design/icons'
import { message, Upload } from 'antd'
import styles from './index.module.scss'
import * as XLSX from 'xlsx'
import { useDispatch } from 'react-redux'
import dayjs from 'dayjs'
import { batchImport } from '@/store/actions/Import'
import { useHistory } from 'react-router-dom'

const Import = () => {
  const { Dragger } = Upload
  const dispatch = useDispatch()
  const history = useHistory()
  const handleByImportExcel = async (e) => {
    message.info('解析中...')
    const fileReader = new FileReader()
    fileReader.onload = async (event) => {
      try {
        const { result } = event.target
        // 以二进制流方式读取得到整份excel表格对象
        const workbook = XLSX.read(result, { type: 'binary', cellDates: true })
        // 存储获取到的数据
        let data = {}
        // 遍历每张工作表进行读取（这里默认只读取第一张表）
        for (const sheet in workbook.Sheets) {
          let tempData = []
          // esline-disable-next-line
          if (workbook.Sheets.hasOwnProperty(sheet)) {
            // 利用 sheet_to_json 方法将 excel 转成 json 数据
            data[sheet] = tempData.concat(
              XLSX.utils.sheet_to_json(workbook.Sheets[sheet])
            )
          }
        }
        //上传成功啦,data为上传后的数据
        data = data['Sheet1'].map((item) => {
          return {
            mobile: item['手机号'],
            username: item['姓名'],
            timeOfEntry: dayjs(item['入职日期']).format('YYYY-MM-DD'),
            correctionTime: dayjs(item['转正日期']).format('YYYY-MM-DD'),
            workNumber: item['工号'],
          }
        })
        await dispatch(batchImport(data))
        history.push('/home/employees')

        message.success('上传成功！')
      } catch (e) {}
    }
    fileReader.readAsBinaryString(e.file)
  }
  return (
    <div className={styles.root}>
      <Dragger
        name="importExcel"
        accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        beforeUpload={() => false}
        onChange={handleByImportExcel}
        showUploadList={false}
      >
        <p className="ant-upload-drag-icon">
          <InboxOutlined />
        </p>
        <p className="ant-upload-text">单击或拖动文件到此区域进行上传</p>
        {/*<p className="ant-upload-hint">仅支持上传xlsx文件</p>*/}
      </Dragger>
    </div>
  )
}

export default Import
